import axios from 'axios';
// import {getRedirectPath} from '../utils/utils';
const REGISTER_SUCCESS = "REGISTER_SUCCESS";//注册成功
const LOGIN_SUCCESS = "LOGIN_SUCCESS";//登录成功
const LOAD_DATA = "LOAD_DATA";//获取数据
const ERROR_MGS = "ERROR_MSG";//错误信息

//初始化状态
const initState = {
    redirectTo: "",//跳转页面
    isAuth: false,
    msg: "",//回调信息
    userPhone: "",
    userPassword: "",
    repeatPassword: "",
    authCode: ""//验证码
};

//返回错误信息
function errorMsg(msg) {
    return {msg, type: ERROR_MGS}
}

//返回登录成功信息
function loginSuccess(data) {
    return {type: LOGIN_SUCCESS, payload: data};
}

//返回注册成功信息
function registerSuccess(data) {
    return {type: REGISTER_SUCCESS, payload: data};
}
//返回用户信息
export function loadData(userInfo) {
    return {type:LOAD_DATA,payload:userInfo}
}
//创建reducer
export function user(state = initState, action) {
    switch (action.type) {
        case REGISTER_SUCCESS:
            return {...state, msg: "", redirectTo: "/login", isAuth: true, ...action.payload};
        case LOGIN_SUCCESS:
            return {...state, msg: "", redirectTo: "/Main", isAuth: true, ...action.payload};
        case LOAD_DATA:
            return {...state,...action.payload};
        case ERROR_MGS:
            return {...state, isAuth: false, msg: action.msg};
        default:
            return state;
    }
}

//接收参数 设置注册验证
export function register({userPhone, userPassword, repeatPassword, authCode}) {
    if (!userPhone || !userPassword || !repeatPassword || !authCode) {
        return errorMsg("输入不完整");
    }
    if (authCode !== "123123") {
        return errorMsg("验证码不匹配");
    }
    if (userPassword !== repeatPassword) {
        return errorMsg("两次密码不一致");
    }
    return dispatch => {
        axios.post('/user/register', {userPhone, userPassword})
            .then((res) => {
                console.log(res);
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(registerSuccess({userPhone, userPassword}));
                } else {
                    dispatch(errorMsg(res.data.msg));
                }
            });
    }
}

//接受参数 设置登录验证
export function login({userPhone, userPassword}) {
    if (!userPhone || !userPassword) {
        return errorMsg("输入不完整");
    }
    return dispatch => {
        axios.post('/user/login', {userPhone, userPassword})
            .then((res) => {
                console.log(res);
                if (res.status === 200 && res.data.code === 0) {
                    dispatch(loginSuccess(res.data.data));
                } else {
                    dispatch(errorMsg(res.data.msg));
                }
            })
    }
}

